package com.gzz.orchid.context.application.rbac.convert;

import com.gzz.orchid.context.application.rbac.command.ModuleSaveCmd;
import com.gzz.orchid.context.application.rbac.pojo.ModuleDto;
import com.gzz.orchid.context.application.rbac.pojo.ModuleVo;
import com.gzz.orchid.context.infrastructure.definition.Action;
import com.gzz.orchid.context.infrastructure.definition.Status;
import com.gzz.orchid.context.infrastructure.persistence.entity.sys.SysModulePo;
import org.mapstruct.*;
import org.mapstruct.factory.Mappers;

import java.util.Set;

/**
 * @author higmd
 */
@Mapper(unmappedTargetPolicy = ReportingPolicy.IGNORE, imports = {Action.class, Status.class})
public interface ModuleConverter {
    ModuleConverter INSTANCE = Mappers.getMapper(ModuleConverter.class);


    @Mappings({
            @Mapping(target = "actions", ignore = true)
    })
    SysModulePo mapPo(ModuleSaveCmd cmd);

    @Mappings({
            @Mapping(target = "actions", qualifiedByName = {"calcActionResult"})
    })
    void updatePo(@MappingTarget SysModulePo po, ModuleSaveCmd cmd);

    @Mappings({
            @Mapping(target = "status", expression = "java(Status.parse(po.getStatus()))")
    })
    ModuleDto mapDto(SysModulePo po);

    @Mappings({
            @Mapping(target = "actions", expression = "java(Action.parseSet(po.getActions()))"),
            @Mapping(target = "status", expression = "java(Status.parse(po.getStatus()))")
    })
    ModuleVo mapVo(SysModulePo po);

    /**
     * 计算权限
     */
    @Named("calcActionResult")
    default Integer calcActionResult(Set<String> actions) {
        if (actions == null || actions.isEmpty()) {
            return 0;
        }
        return actions.stream().map(Integer::parseInt).map(Action::parse).mapToInt(Action::getValue).sum();
    }
}
